const { API_SNZO_URL, API_SNZO_FILE_URL } = require("../../../utils/wxapi")
const wxapi = require("../../../utils/wxapi")
const app = getApp();
// pages/center/upload/upload.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userSpace: null,
    typeIndex: null,
    domainIndex: null,
    worksTypeOfData: [],
    sortOfData: [],
    thumbImgUrl: null,
    worksImgInfo: null,
    worksName: null,
    standby2: null,
    worksDetail: null,
    agreementMsg: null,
    pageContainerTitle: null,
    showPageContainer: false,
    worksFileList: [],
    worksFormValue: null,
    apiSnzoUrl: API_SNZO_FILE_URL,
    isConfirm: false,
    isHandle: false,
    isUnitUser: false,
    uploadStatus: false
  },

  /**
   * 校验用户类别
   * status 200 集团用户 status 400 个人用户
   */
  checkUserType() {
    wxapi.selectUnitUserByStk({ stk: app.globalData.userInfo.cardNo }).then(res => {
      if (res.status === 200) {
        this.setData({
          isUnitUser: true
        })
      } else if (res.status === 400) {
        this.setData({
          isUnitUser: false
        })
        this.getSpaceMsg();
      }
    })
  },

  /**
   * 获取用户空间信息
   */
  getSpaceMsg() {
    wxapi.selectSpaceMsg({ stk: app.globalData.userInfo.cardNo }).then(res => {
      if (res.status === 200) {
        if (res.data.avliableSpace) {
          this.setData({
            userSpace: res.data
          })
        } else {
          wx.showModal({
            title: '提示信息',
            content: '空间不足或空间已到期。',
            showCancel: false,
            complete: (res) => {
              if (res.confirm) {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              }
            }
          })
        }
      }
    })
  },

  /**
   * 获取类型
   */
  getWorksType() {
    wxapi.getStNumWorksType({ standby3: 1 }).then(res => {
      if (res.status === 200) {
        this.setData({
          worksTypeOfData: res.data.reverse()
        })
      }
    })
  },

  /**
   * 获取专业
   */
  getSortType() {
    const standby4 = this.data.worksTypeOfData[this.data.typeIndex].id;
    wxapi.getStNumWorksType({ standby4 }).then(res => {
      if (res.status === 200) {
        this.setData({
          sortOfData: res.data
        })
      }
    })
  },

  /**
   * 艺术品类型切换
   * @param {*} e 
   */
  bindWorksPickerChange(e) {
    const typeIndex = e.detail.value;
    this.setData({
      typeIndex,
      domainIndex: null
    })
    this.getSortType();
  },

  /**
   * 艺术品专业切换
   * @param {*} e 
   */
  bindSortPickerChange(e) {
    const domainIndex = e.detail.value;
    this.setData({
      domainIndex
    })
  },

  /**
   * 选择封面图
   */
  uploadThumb() {
    this.data.uploadStatus = true;
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res) => {
        wx.uploadFile({
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          url: this.data.apiSnzoUrl + '/stNumUpload/uploadImg',
          success: (result) => {
            const fileResult = JSON.parse(result.data);
            if (fileResult.status === 200) {
              this.setData({
                thumbImgUrl: fileResult.data.staticPath
              })
            }
          },
          fail: (res) => {
            wx.showModal({
              title: '提示信息',
              content: res.msg || res.message,
              showCancel: false
            })
          }
        })
      },
      fail: (res) => {
        wx.showModal({
          title: '提示信息',
          content: '选择文件失败',
        })
      }
    })
  },

  /**
   * 选择艺术品
   */
  uploadWorks() {
    this.data.uploadStatus = true;
    wx.chooseMedia({
      count: 1,
      success: (res) => {
        var url = '';
        if (res.type === 'image') {
          url = '/stNumUpload/uploadImg';
        } else if (res.type === 'video') {
          url = '/stNumUpload/uploadVideo';
        }
        wx.uploadFile({
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          url: this.data.apiSnzoUrl + url,
          success: (result) => {
            const fileResult = JSON.parse(result.data);
            if (fileResult.status === 200) {
              this.data.worksFileList = [];
              const tabStnumWorksItem = {
                occupiedSpace: fileResult.data.occupiedSpace,
                saveAddress: fileResult.data.saveAddress,
                realPath: fileResult.data.realPath,
                standby1: fileResult.data.staticPath,
                stkNum: app.globalData.userInfo.cardNo,
                standby2: res.type,
              };
              this.data.worksFileList.push(tabStnumWorksItem);
              if (!this.data.isUnitUser) { this.getSpaceMsg(); }
              this.setData({
                worksFileList: this.data.worksFileList
              })
              if (this.data.worksTypeOfData[this.data.typeIndex].id !== 7) {
                this.setData({
                  thumbImgUrl: tabStnumWorksItem.standby1
                })
              }
            }
          },
          fail: (res) => {
            wx.showModal({
              title: '提示信息',
              content: res.msg || res.message,
              showCancel: false
            })
          }
        })
      },
      fail: (res) => {
        wx.showModal({
          title: '提示信息',
          content: '选择文件失败',
          showCancel: false
        })
      }
    })
  },

  /**
   * 上传艺术品
   * @param {*} e 
   */
  submitWorks(e) {
    const value = e.detail.value;
    if (this.data.typeIndex === null || !value.standby6 || !value.worksName || !value.standby2 || this.data.worksFileList.length === 0) {
      wx.showModal({
        title: '提示信息',
        content: '请填写带*号必填信息',
        showCancel: false
      })
      return false;
    } else {
      if (this.data.isHandle) {
        return;
      }
      this.data.isHandle = true;
      this.data.worksFormValue = value;
      this.getAgreement();
    }

  },

  /**
   * 获取艺术品创作承诺书
   */
  getAgreement() {
    if (this.data.agreementMsg) {
      this.data.isHandle = false;
      this.setData({
        showPageContainer: true
      })
    } else {
      wxapi.getSnzoNewsMsgById({ id: 31833 }).then(res => {
        this.data.isHandle = false;
        if (res.status === 200) {
          this.setData({
            agreementMsg: res.data.newsContent,
            pageContainerTitle: res.data.newsTitle,
            showPageContainer: true
          })
        }
      })
    }

  },

  /**
   * 隐藏遮罩
   */
  hidePageContainer() {
    this.setData({
      showPageContainer: false
    })
  },

  /**
   * 确认
   */
  confirmPageContainer() {
    if (this.data.isConfirm) { return; }
    this.data.isConfirm = true;
    const bodyParams = {
      tabStnumWorksMsg: {
        worksType: this.data.worksTypeOfData[this.data.typeIndex].id,
        standby6: this.data.sortOfData[this.data.domainIndex].id,
        standby2: this.data.worksFormValue.standby2,
        standby3: this.data.worksFormValue.standby3,
        worksDetail: this.data.worksFormValue.worksDetail,
        worksName: this.data.worksFormValue.worksName,
        worksStatus: 0,
        standby1: app.globalData.userInfo.cardNo,
        worksPhoto: this.data.thumbImgUrl
      },
      tabStnumWorkses: this.data.worksFileList
    }
    wx.showLoading({
      title: '上传中...',
    })
    wxapi.inserWorks(bodyParams).then(res => {
      wx.hideLoading()
      this.data.isConfirm = false;
      if (res.status === 200) {
        wx.showToast({
          title: '长传成功',
          success: () => {
            this.initData();
            wx.switchTab({
              url: '/pages/center/center',
            })
          }
        })
      } else {
        wx.showToast({
          title: '上传失败',
          icon: 'error'
        })
      }
    })
  },

  /**
   * 初始化数据
   */
  initData() {
    this.setData({
      userSpace: null,
      typeIndex: null,
      domainIndex: null,
      thumbImgUrl: null,
      worksImgInfo: null,
      worksName: '',
      standby2: '',
      worksDetail: null,
      agreementMsg: null,
      pageContainerTitle: null,
      showPageContainer: false,
      worksFileList: [],
      worksFormValue: null,
      isConfirm: false,
      uploadStatus: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
    if (app.globalData.token) {
      if (!this.data.uploadStatus) { this.initData() };
      this.getWorksType();
      this.checkUserType();
      // this.getSpaceMsg()
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})